package cfl.activemq.com.queues;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

import cfl.activemq.com.config.ActiveMQConfig;

/**
 * 生产者
 * @author chenfenli
 *
 */
public class QueuesProducer {

	public static final int 	SENDNUM = 10;										// 发送的消息数
	
	public static void main(String[] args) {
		ConnectionFactory connectionFactory;
		Connection connection = null;
		try {
			// 1.创建链接工厂
			connectionFactory = new ActiveMQConnectionFactory(ActiveMQConfig.UASENAME, ActiveMQConfig.PASSWORD, ActiveMQConfig.BROKEURL);
		
			// 2.创建链接对象
			connection = connectionFactory.createConnection();
			
			// 3.启动链接
			connection.start();
			
			// 4.创建session会话 true:并且开启事务
			Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
			
			// 5.创建消息队列,名称为：Queues
			Destination destination = session.createQueue("Queues测试");
			
			// 6.创建生产者
			MessageProducer messageProducer = session.createProducer(destination);
			
			// 7.发送消息
			sendMessage(session, messageProducer);
			
			// 8.提交事务
			session.commit();
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			// 关闭链接
			if(connection != null) {
				try {
					connection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 发送消息
	 * @param session
	 * @param messageProducer 生产者
	 * @throws JMSException 
	 */
	public static void sendMessage(Session session, MessageProducer messageProducer) throws JMSException {
		for(int i = 0; i < SENDNUM; i++) {
			Message message = session.createTextMessage("activemq_queues 发送的消息 " + i);
			messageProducer.send(message);
		}
	}
}
